package net.cnki.sunny.service.impl;

import cn.hutool.core.exceptions.ValidateException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.cnki.sunny.base.BaseService;
import net.cnki.sunny.model.dto.UserDTO;
import net.cnki.sunny.model.entity.User;
import net.cnki.sunny.model.mapper.UserMapper;
import net.cnki.sunny.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends BaseService<User> implements UserService {

    @Resource
    private UserMapper userMapper;

    public List<User> getUserList() {
        return selectAll();
    }

    @Override
    public User selectByUser(User user) {
        return selectOne(user);
    }

    @Override
    public List<User> selectListByUser(User user){
        return select(user);
    }

    @Override
    public List<User> selectByCondition(UserDTO userDTO){
       return userMapper.selectByCondition(userDTO);
    }

    /**
     * 根据用户名查询
     */
    @Override
    public User selectByUsername(String username) {
        User condition = new User();
        condition.setUsername(username);
        return selectOne(condition);
    }

    @Override
    public void addUser(User user) {
        //用户名不能重复
        User userExist = selectByUsername(user.getUsername());
        if (ObjectUtils.isEmpty(userExist)) {
            user.setCreateTime(new Date(System.currentTimeMillis()));
            user.setPassword("123456");
            insertSelective(user);
        } else {
            throw new ValidateException("用户名已存在");
        }
    }

    @Override
    public void modifyUser(User user) {
        //用户存在
        User userExist = selectByPrimaryKey(user.getId());
        if (ObjectUtils.isEmpty(userExist)) {
            throw new ValidateException("用户不存在");
        }
        //用户名不能重复
        User condition = new User();
        condition.setUsername(user.getUsername());
        List<User> userList = select(condition);
        if ((userExist.getUsername().equals(user.getUsername()) && userList.size() > 1)
                || (!userExist.getUsername().equals(user.getUsername()) && userList.size() > 0)) {
            throw new ValidateException("用户名已存在");
        }
        user.setUpdateTime(new Date(System.currentTimeMillis()));
        updateByPrimaryKeySelective(user);
    }

    @Override
    public void deleteUser(Integer id) {
        deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<User> getUserList(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPageNum(), userDTO.getPageSize());
        return new PageInfo<>(selectByCondition(userDTO));
    }
}
